<template>
  <div class="fix-width-frame">
    <div class="label-title">设置收货地址</div>
    <p>
      <span class="select-gift">您当前选择的礼品是： {{gift.resourceDesc}}</span>
    </p>
    <div class="main">
      <div class="tip-container">
        <div class="tip">
          <span>下单须知：</span>当日18点前下单，当日发货并输出物流信息，超过18点则次日发货并输出信息
        </div>
        <div class="tip">
          <span>发货须知：</span>【菜鸟-申通-石狮】福建泉州发货 【菜鸟-百世汇通-义乌】浙江义乌发货
        </div>
      </div>

      <div class="table-wrapper">
        <div class="table-header">
          <div class="table-header-title">确认快递详情</div>
        </div>

        <div class="table-row">
          <div class="table-cell-inputlabel">选择快递：</div>
          <el-select
            class="table-cell-input"
            v-model="express"
            placeholder="请选择快递"
            @change="expressChanged"
          >
            <el-option
              v-for="item in expressOptions"
              :key="item.id"
              :label="item.kkDesc"
              :value="item.kkType"
            ></el-option>
          </el-select>
        </div>
        <el-row class="table-row-footer" type="flex" align="middle">
          <el-col :span="3" class="table-row-content">
            <div class="table-cell">您的单价:</div>
          </el-col>
          <el-col :span="3" class="table-row-content">
            <div class="table-cell">{{price}}</div>
          </el-col>
          <el-col :span="3" class="table-row-content">
            <div class="table-cell">您的等级:</div>
          </el-col>
          <el-col :span="3" class="table-row-content">
            <div class="table-cell">{{levelDesc}}</div>
          </el-col>
        </el-row>
      </div>

      <div class="table-wrapper">
        <div class="table-header">
          <div class="table-row-content">
            <div class="table-header-title">确认发货人地址
              <el-button type="text" class="deposit" @click="toAddressManager()">点击管理发货地址>></el-button>
            </div>
          </div>
        </div>
        <div class="table-row">
          <div class="table-cell-inputlabel">选择发货人：</div>
          <el-select
            class="table-cell-input"
            v-model="address"
            placeholder="请选择发货人地址"
            value-key="id"
          >
            <el-option
              v-for="item in addressOptions"
              :key="item.id"
              :label="item.address"
              :value="item"
            ></el-option>
          </el-select>
        </div>
        <div class="table-row">
          <div class="table-cell-inputlabel">快递重量
            <span style="color: red">*</span>:
          </div>
          <el-input class="table-cell-input" placeholder="请输入重量" v-model="weight">
            <template slot="append">kg</template>
          </el-input>
          <span style="color: red; font-size: 14px;">请填写您快递包裹的真实重量</span>
        </div>
      </div>

      <div class="table-wrapper" style="margin-top: 40px;">
        <div class="table-header">
          <div class="table-row-content">
            <div class="table-header-title">备注信息</div>
          </div>
        </div>
        <div class="table-row">
          <div class="table-cell-inputlabel">订单备注：</div>
          <el-input class="table-cell-input" placeholder="如货号：NK001-黑色：175" v-model="memo"></el-input>
          <span style="color: red; font-size: 14px;">用于打印在面单货品名称</span>
        </div>
      </div>

      <div class="table-wrapper" style="margin-top: 40px;">
        <div class="table-header">
          <div class="table-row-content">
            <div class="table-header-title">填写收货地址</div>
          </div>
        </div>
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="批量导入" name="first">
            <div>
              <div class="table-row-content">
                <div style="font-size: 14px;" class="table-cell">
                  <!-- <p>
                              说明: 根据上面的格式，填入收货地址，一行对应一个地址。或者也可批量导入地址，每次导入不可超过3000个地址<br/>
                  </p>-->
                  <div class="table-row">
                    <div class="table-cell-inputlabel">选择快递：</div>
                    <el-select class="table-cell-input" v-model="platform" placeholder="请选择模版">
                      <el-option
                        v-for="item in platforms"
                        :key="item.type"
                        :label="item.label"
                        :value="item.type"
                      ></el-option>
                    </el-select>
                  </div>

                  <el-upload
                    class="upload-demo"
                    :action="uploadAction"
                    :on-success="uploadFile"
                    :on-error="uploadFileFail"
                    :on-change="loadFile"
                    :on-remove="removeFile"
                    :auto-upload="false"
                    :limit="1"
                  >
                    <el-button type="primary">上传文件</el-button>
                    <div
                      slot="tip"
                      class="el-upload__tip"
                    >(支持导入CSV或excel文件，文件中需要包含 订单号、客户姓名、客户地址、联系电话 这些信息)</div>
                  </el-upload>

                  <p>你也可以下载模版，按模版内容填写后上传，
                    <a href="../static/template.xlsx" download="导入模版.xlsx">
                      <el-button type="text">下载模版</el-button>
                    </a>
                  </p>
                </div>
              </div>
            </div>
          </el-tab-pane>

          <el-tab-pane label="手动输入" name="second">
            <div>
              <div class="table-row-content">
                <div style="font-size: 14px;" class="table-cell">
                  <p>
                    <strong style="color: red;">标准格式:</strong> 订单号 省市县区地址 姓名 手机
                  </p>
                  <p>
                    <strong style="color: red;">举例:</strong> 80000000001 江苏省苏州市吴中区XX路XX号 张三 13088888888
                  </p>
                  <p>或</p>
                  <p>
                    <strong style="color: red;">淘宝格式:</strong> 订单号 姓名, 手机, 省 市 县区 地址, 邮编（可选）
                  </p>
                  <p>
                    <strong style="color: red;">举例:</strong> 80000000001 张三，13088888888，江苏省 苏州市 吴中区 XX路XX号，523900
                  </p>
                </div>
              </div>
            </div>
            <div class="table-wrapper">
              <div class="table-row" style="width: 700px; height: 200px;">
                <el-input
                  type="textarea"
                  :rows="10"
                  placeholder="订单号 省市县区地址 姓名 手机
  或
  省市县区地址 姓名 手机"
                  v-model="inputAddressRows"
                  style="height: 150px;"
                ></el-input>
                <div
                  style="height: 50px; border-top: 1px solid #dcdcdc; line-height: 50px; text-align: right;"
                >
                  <span style="color: #222;">填写完毕请点击</span>
                  <el-button
                    type="primary"
                    plain
                    style="margin: 0 5px; width: 130px; height: 30px; padding: 0;"
                    @click="verifyAddress()"
                  >验证地址格式</el-button>
                </div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>

        <el-row style="margin: 50px auto">
          <div class="block batch-table">
            <el-table :data="tableData" :row-key="row => row.index" style="width: 100%">
              <!--<el-table-column type="expand">
                                <template scope="props">
                                    <el-form label-position="left" inline class="demo-table-expand">
                                        <el-form-item label="姓名">
                                            <span>{{ props.row.receiverName }}</span>
                                        </el-form-item>
                                        <el-form-item label="电话">
                                            <span>{{ props.row.receiverTel }}</span>
                                        </el-form-item>
                                        <el-form-item label="地址">
                                            <span>{{ props.row.receiverAddress }}</span>
                                        </el-form-item>
                                    </el-form>
                                </template>
              </el-table-column>-->
              <el-table-column type="index" width="100"></el-table-column>
              <el-table-column label="订单编号" prop="outOrderId" width="200"></el-table-column>
              <el-table-column label="姓名" prop="receiverName" width="150"></el-table-column>
              <el-table-column label="电话" prop="receiverTel" width="250"></el-table-column>
              <el-table-column label="地址" prop="receiverAddress"></el-table-column>
              <!--<el-table-column
                                label="验证结果">
                                <template scope="scope">
                                    <div v-show="scope.row.state != undefine">
                                        <el-button type="text" v-show="scope.row.state=true">正确</el-button>
                                        <el-button type="text" v-show="scope.row.state=false">错误</el-button>
                                    </div>
                                </template>
                                
              </el-table-column>-->
            </el-table>
          </div>
        </el-row>
      </div>

      <div class="table-wrapper">
        <el-row class="table-header" type="flex" align="middle">
          <el-col :span="24" class="table-row-content">
            <div class="table-header-title">确认付款信息</div>
          </el-col>
        </el-row>

        <el-row class="table-row-footer" type="flex" align="middle">
          <el-col :span="4" class="table-row-title">
            <div class="table-cell">快递单价：</div>
          </el-col>
          <el-col :span="4" class="table-row-content">
            <div class="table-cell">{{price}}</div>
          </el-col>
          <el-col :span="4" class="table-row-title">
            <div class="table-cell">快递数量：</div>
          </el-col>
          <el-col :span="4" class="table-row-content">
            <div class="table-cell">{{tableData.length}}</div>
          </el-col>
          <el-col :span="4" class="table-row-title">
            <div class="table-cell">应付款额：</div>
          </el-col>
          <el-col :span="4" class="table-row-content">
            <div class="table-cell">{{totalPrice}}</div>
          </el-col>
        </el-row>
        <el-row class="table-row-footer" type="flex" align="middle">
          <el-col :span="24" class="table-row-content">
            <div class="table-cell">
              当前账户余额： ¥{{ balance/100 }}金币
              <el-button type="text" class="deposit" @click="toDeposit()">点击去充值>></el-button>
            </div>
          </el-col>
        </el-row>
      </div>

      <el-row style="margin: 20px auto;">
        <el-button type="primary" @click="onOrderCreate()" style="width: 160px; height: 40px;">提交订单</el-button>
      </el-row>

      <el-dialog title="确认订单" v-show="batchOrderDialogVisible" class="batch-dialog">
        <el-form :model="selectBatchOrder">
          <template>
            <div class="block batch-table">
              <el-table :data="tableData" :row-key="row => row.index" style="width: 100%">
                <el-table-column type="index" width="100"></el-table-column>
                <el-table-column label="订单编号" prop="outOrderId" width="200"></el-table-column>
                <el-table-column label="姓名" prop="receiverName" width="150"></el-table-column>
                <el-table-column label="电话" prop="receiverTel" width="250"></el-table-column>
                <el-table-column label="地址" prop="receiverAddress"></el-table-column>
              </el-table>
              <!--<div class="Pagination">-->
              <!--<el-pagination-->
              <!--@size-change="handleSizeChange"-->
              <!--@current-change="handleCurrentChange"-->
              <!--:current-page="currentPage"-->
              <!--:page-size="20"-->
              <!--layout="total, prev, pager, next"-->
              <!--:total="total">-->
              <!--</el-pagination>-->
              <!--</div>-->
            </div>
          </template>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="batchOrderDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="batchOrderConfirmClick()">下单</el-button>
        </div>
      </el-dialog>

      <el-dialog title="确认单个订单" v-show="singleOrderDialogVisible">
        <el-form :model="selectSingleOrder">
          <el-form-item label="数量" label-width="100px">
            {{selectSingleOrder.outAmount}}
            <!--<el-input v-model="singleOrderDialogForm.itemId" auto-complete="off"></el-input>-->
          </el-form-item>

          <el-form-item label="金额" label-width="100px">
            {{selectSingleOrder.orderAmount}}
            <!--<el-input v-model="singleOrderDialogForm.imageUrl" auto-complete="off"></el-input>-->
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="singleOrderDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="orderConfirmClick()">确定下单</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import headTop from "@/components/headTop";
import { orderCreate, orderConfirm } from "@/api/order";
import { getExpressList } from "@/api/info";
import { getPriceList, getGift } from "@/api/gift";
import { getAddressAll } from "@/api/address";
// import {getUserAccount} from '@/api/myinfo'
import { level } from "@/utils/cookie";
import { getUserAccount, getUserInfo } from "@/api/myinfo";
import csv from "csvtojson";
// import XLSX from 'xlsx'

export default {
  computed: {
    totalPrice: function() {
      return (this.price * this.tableData.length).toFixed(2);
    },

    uploadAction: function() {
      return "/v01/user/order/check?kkType=" + this.express;
    }
  },

  data() {
    return {
      uploadFiles: [],
      idErrorRows: [],
      nameErrorRows: [],
      addressErrorRows: [],
      telErrorRows: [],

      uploadLoading: undefined,
      expressOptions: [],
      express: "",
      address: undefined,
      addressOptions: [],
      price: 0,
      balance: 0,
      weight: 0,
      memo: "",
      inputAddressRows: "",
      priceMap: [],
      formData: {},
      activeName: "first",
      platform: "tb",
      platforms: [
        {
          label: "淘宝天猫",
          type: "tb"
        },
        {
          label: "拼多多",
          type: "pdd"
        },
        {
          label: "京东",
          type: "jd"
        },
        {
          label: "礼品网模版",
          type: "tpl"
        }
      ],
      singleOrderForm: {
        giftId: 1,
        orderCode: "300102",
        outId: "asdsa",
        outType: "TAOBAO"
      },
      orderForm: {
        receiverName: "",
        receiverTel: "",
        receiverAddress: ""
      },
      orderConfirmDto: {
        id: "9",
        status: "ENABLE"
      },

      batchOrderDialogVisible: false,
      selectBatchOrder: {},

      singleOrderDialogVisible: false,
      singleOrderDialogForm: {},
      selectSingleOrder: {
        outAmount: 0,
        orderAmount: 0
      },

      tableData: [],
      currentPage: 1,
      total: 0,

      batchFileDetailDto: undefined,

      singleConfirmDto: {
        id: 0
      },

      orderConfirm: {
        id: "9",
        status: "ENABLE"
      },
      textarea: "",
      // show
      showSingle: true,
      levelDesc: "",
      gift: ""
    };
  },
  components: {
    headTop
  },
  mounted() {
    // this.initData();
  },

  created() {
    this.initData();
  },
  methods: {
    async initData() {
      this.getGift();
      this.getExpressList();
      this.getAllAddress();
      this.getBalance();
      this.getPrices();
      this.getlevel();
    },

    async getlevel() {
      try {
        // const account = await getAccount();
        const result = await getUserAccount();
        const info = await getUserInfo();
        if (result.status === 200 && result.data.code === 200) {
          let data = result.data;
          //   this.userName = data.data.userName
          //   this.balance = data.data.balance
          this.levelDesc = info.data.data.levelDesc;
        }
      } catch (err) {
        console.log(err);
      }
    },
    async getGift() {
      try {
        // const account = await getAccount();
        const result = await getGift(this.$route.query.giftId);
        if (result.status === 200 && result.data.code === 200) {
          //   this.userName = data.data.userName
          //   this.balance = data.data.balance
          this.gift = result.data.data;
        }
      } catch (err) {
        console.log(err);
      }
    },
    toDeposit() {
      this.$router.push("points");
    },

    toAddressManager() {
      this.$router.push("address");
    },

    verifyAddress() {
      this.batchFileDetailDto = undefined;
      let verifyData = [];
      let lines = this.inputAddressRows.split("\n");
      // .split("\n")[1].trim().split(/\s+/)
      for (let i = 0; i < lines.length; i++) {
        let line = lines[i];
        if (line.length === 0) {
          continue;
        }
        let format1 = line.trim().split(/[,，]/);
        if (format1.length === 3 || format1.length === 4) {
          let first = format1[0].trim().split(/\s+/);
          if (first.length === 2) {
            verifyData.push({
              outOrderId: first[0].trim(),
              receiverName: first[1].trim(),
              receiverTel: format1[1].trim(),
              receiverAddress: format1[2].trim()
            });
          } else {
            verifyData.push({
              receiverName: format1[0].trim(),
              receiverTel: format1[1].trim(),
              receiverAddress: format1[2].trim()
            });
          }

          continue;
        } else {
          let items = line.trim().split(/\s+/);
          if (items.length === 3) {
            if (!/^\d{11}$/.test(items[2])) {
              this.$message.error(
                `第${i + 1}行记录手机号不对，请修正后重新提交`
              );
              return;
            }

            if (items[0].length < 6) {
              this.$message.error(`第${i + 1}行记录地址不对，请修正后重新提交`);
              return;
            }
            verifyData.push({
              receiverName: items[1],
              receiverTel: items[2],
              receiverAddress: items[0]
            });
            continue;
          } else if (items.length === 4) {
            if (!/^\d{11}$/.test(items[3])) {
              this.$message.error(
                `第${i + 1}行记录手机号不对，请修正后重新提交`
              );
              return;
            }
            if (items[1].length < 6) {
              this.$message.error(`第${i + 1}行记录地址不对，请修正后重新提交`);
              return;
            }
            verifyData.push({
              outOrderId: items[0],
              receiverName: items[2],
              receiverTel: items[3],
              receiverAddress: items[1]
            });
            continue;
          }
        }
        //  else {
        this.$message.error(`第${i + 1}行记录格式错误，请修正后重新提交`);
        return;
        // }
      }
      this.tableData = verifyData;
    },

    expressChanged(v) {
      for (let priceItem of this.priceMap) {
        if (
          priceItem.kkType === v &&
          priceItem.giftId == this.$route.query.giftId
        ) {
          this.price = priceItem.price / 100;
          return;
        }
      }

      this.price = 0;
      this.$message.error(`当前礼品不支持此快递`);
      // this.price = this.priceMap[`${v}${this.$route.query.giftId}`]
    },

    handleClick(tab, event) {
      this.tableData = [];
    },
    submitForm1() {},

    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.offset = (val - 1) * this.limit;
      // this.getFoods()
    },

    async getBalance() {
      try {
        const result = await getUserAccount();
        if (result.status === 200) {
          this.balance = result.data.data.balance;
        }
      } catch (err) {
        console.log(err);
      }
    },

    async getPrices() {
      try {
        const priceResult = await getPriceList(false);
        if (priceResult.status === 200) {
          this.priceMap = priceResult.data.data;
        } else {
          throw new Error("快递列表获取失败");
        }
      } catch (err) {
        console.log(err);
      }
    },

    async getExpressList() {
      try {
        const result = await getExpressList();
        if (result.status === 200) {
          this.expressOptions = result.data.data.filter(e => {
            return e.status === "ENABLE" && e.kkType.search(/^API_/) === -1;
          });
        } else {
          throw new Error("快递列表获取失败");
        }
      } catch (err) {
        console.log(err);
      }
    },

    async getAllAddress() {
      try {
        const result = await getAddressAll();
        if (result.status === 200 && result.data.code === 200) {
          this.addressOptions = result.data.data.map(address => {
            address.address = `${address.name}; ${address.tel}; ${
              address.province
            } ${address.city} ${address.region} ${address.detail}`;
            return address;
          });
        } else {
          throw new Error("获取数据失败");
        }
        // this.getUsers();
      } catch (err) {
        // this.$message.error('发货地址获取失败')
        console.log("获取数据失败", err);
      }
    },
    uploadFile(res, file) {
      this.uploadLoading.close();
      if (res.code === 200) {
        // this.foodForm.image_path = res.image_path;
        this.showConfirmList(res);
        this.showSingle = false;
      } else {
        this.$message.error(res.title);
      }
    },
    uploadFileFail(res) {
      this.uploadLoading.close();
    },

    showConfirmList(returnData) {
      this.tableData = returnData.data.detailDtos;
      this.batchFileDetailDto = returnData.data.fileDetailDto;
      this.total = returnData.page.total;
      this.currentPage = returnData.page.pageIndex;
    },
    // beforeFileUpload (file) {
    //   this.uploadLoading = this.$loading({
    //     lock: true,
    //     text: '正在上传',
    //     spinner: 'el-icon-loading',
    //     background: 'rgba(0, 0, 0, 0.7)'
    //   })
    //                const isRightType = (file.type === 'csv') || (file.type === 'csv');
    //                const isLt2M = file.size / 1024 / 1024 < 2;
    //
    //                if (!isRightType) {
    //                    this.$message.error('上传文件只能是 CSV 格式!');
    //                }
    //                if (!isLt2M) {
    //                    this.$message.error('上传图片大小不能超过 2MB!');
    //                }
    //                return isRightType && isLt2M;
    // },

    async orderConfirmClick(orderConfirmDto) {
      let result = await orderConfirm(this.orderConfirm);
      if (result.status == 200 && result.data.code === 200) {
        this.$message({
          type: "success",
          message: "下单成功"
        });
        this.batchOrderDialogVisible = false;
      } else {
      }
    },

    singleOrderConfirmClick() {
      let confirm = {};
      confirm.id = this.singleConfirmDto.id;
      confirm.status = "ENABLE";
      orderConfirm(confirm);
    },
    batchOrderConfirmClick() {
      if (this.batchFileDetailDto !== undefined) {
        let confirm = {};
        confirm.id = this.batchFileDetailDto.id;
        confirm.status = "ENABLE";
        this.orderConfirmClick(confirm);
      } else {
        let confirm = {};
        confirm.id = this.singleConfirmDto.id;
        confirm.status = "ENABLE";
        this.orderConfirmClick(confirm);
      }
    },
    handleDelete(index) {
      this.activities.splice(index, 1);
    },
    // 创建单个订单
    async inputOrderCreate() {
      const loading = this.$loading({
        lock: true,
        text: "正在加载",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      let formData = {
        giftId: this.$route.query.giftId,
        orderCode: "300102",
        outId: "asdsa",
        outType: "PDD",
        kkType: this.express,
        weight: this.weight,
        addressId: this.address.id,
        address: this.address.address,
        detailDtos: this.tableData
      };
      if (this.memo !== "") {
        formData.memo = this.memo;
      }
      try {
        let result = await orderCreate(formData);
        if (result.status === 200 && result.data.code === 200) {
          let returnData = result.data.data;
          this.selectSingleOrder.outAmount = returnData.outAmount;
          this.selectSingleOrder.orderAmount = returnData.orderAmount;
          this.batchOrderDialogVisible = true;

          this.singleConfirmDto.id = result.data.data.id;
          this.orderConfirm.id = result.data.data.id;
        } else {
          //   this.$message({
          //     type: 'error',
          //     message: result.message
          //   })
        }
        console.log(result);
      } catch (err) {
        console.log(err);
      }
      loading.close();
    },
    // 创建订单
    onOrderCreate() {
      if (this.express === "") {
        this.$message({
          type: "error",
          message: "快递类型不能为空"
        });
        return;
      }
      if (this.address === undefined) {
        this.$message({
          type: "error",
          message: "请选择发货地址"
        });
        return;
      }

      if (this.weight <= 0) {
        this.$message({
          type: "error",
          message: "请输入包裹重量"
        });
        return;
      }

      if (this.tableData.length === 0) {
        this.$message({
          type: "error",
          message: "请先输入收入地址"
        });
        return;
      }
      if (this.batchFileDetailDto !== undefined) {
        this.fileOrderCreate();
      } else {
        this.inputOrderCreate();
      }
    },

    removeFile(file, fileList) {
      this.uploadFiles = fileList;
      this.tableData = [];
    },
    loadFile(file, fileList) {
      this.uploadFiles = fileList;
      this.parseFileForPlatform();
    },
    loadJDSV(file, fileList) {
      this.uploadFiles = fileList;
      // this.loadCSVFromFileConfirmed()
    },
    loadPDDCSV(file, fileList) {
      this.uploadFiles = fileList;
      // this.loadCSVFromFileConfirmed()
    },
    parseFileForPlatform() {
      if (this.platform === "tb") {
        this.loadTBCSV();
      } else if (this.platform === "pdd") {
        this.loadPDDCSV();
      } else if (this.platform === "jd") {
        this.loadJDCSV();
      } else if (this.platform == "tpl") {
        this.loadTemplateExcel();
      }
    },
    async loadTemplateExcel() {
      this.tableData = [];
      this.idErrorRows = [];
      this.nameErrorRows = [];
      this.addressErrorRows = [];
      this.telErrorRows = [];
      if (this.uploadFiles) {
        const loading = this.$loading({
          lock: true,
          text: "正在加载",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)"
        });
        for (let i = 0; i < this.uploadFiles.length; i++) {
          let file = this.uploadFiles[i];
          if (!file) continue;

          let rABS = true;
          let reader = new FileReader();
          reader.onload = async e => {
            let data = e.target.result;
            if (!rABS) data = new Uint8Array(data);
            let workbook = XLSX.read(data, { type: rABS ? "binary" : "array" });
            let jsonArray = XLSX.utils.sheet_to_json(
              workbook.Sheets[workbook.SheetNames[0]]
            );
            this.tableData = jsonArray.map((e, i) => {
              let idre = /(=")?(\d*)"?/;
              let id = e["订单编号"].replace(idre, "$2");
              let telre = /'?(.*)/;
              let tel = String(e["联系手机"]).replace(telre, "$1");
              let order = {
                outOrderId: id,
                receiverName: e["收货人姓名"],
                receiverAddress: e["收货地址"],
                receiverTel: tel
              };

              this.checkError(order, i);

              return order;
            });

            this.showError();

            loading.close();
          };
          if (rABS) reader.readAsBinaryString(file.raw);
          else reader.readAsArrayBuffer(file.raw);
        }
      }
    },
    async loadJDCSV() {
      this.tableData = [];
      this.idErrorRows = [];
      this.nameErrorRows = [];
      this.addressErrorRows = [];
      this.telErrorRows = [];
      if (this.uploadFiles) {
        const loading = this.$loading({
          lock: true,
          text: "正在加载",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)"
        });
        for (let i = 0; i < this.uploadFiles.length; i++) {
          let file = this.uploadFiles[i];
          if (!file) continue;

          let csvreader = csv({
            noheader: false,
            // output: "csv",
            trim: true
          });
          let reader = new FileReader();
          reader.onload = async e => {
            const jsonArray = await csvreader.fromString(e.target.result);
            this.tableData = jsonArray.map((e, i) => {
              let idre = /(=")?(\d*)"?/;
              let id = e["订单号"].replace(idre, "$2");
              let telre = /'?(.*)/;
              let tel = e["联系电话"].replace(telre, "$1");
              let order = {
                outOrderId: id,
                receiverName: e["客户姓名"],
                receiverAddress: e["客户地址"],
                receiverTel: tel
              };

              this.checkError(order, i);

              return order;
            });

            this.showError();

            loading.close();
          };
          reader.readAsText(file.raw, "GB2312");
        }
      }
    },
    async loadPDDCSV() {
      this.tableData = [];
      this.idErrorRows = [];
      this.nameErrorRows = [];
      this.addressErrorRows = [];
      this.telErrorRows = [];
      if (this.uploadFiles) {
        const loading = this.$loading({
          lock: true,
          text: "正在加载",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)"
        });
        for (let i = 0; i < this.uploadFiles.length; i++) {
          let file = this.uploadFiles[i];
          if (!file) continue;

          let csvreader = csv({
            noheader: false,
            // output: "csv",
            trim: true
          });
          let reader = new FileReader();
          reader.onload = async e => {
            const jsonArray = await csvreader.fromString(e.target.result);
            this.tableData = jsonArray.map((e, i) => {
              let idre = /(=")?(\d*)"?/;
              let id = e["订单号"].replace(idre, "$2");
              let telre = /'?(.*)/;
              let tel = e["手机"].replace(telre, "$1");
              let order = {
                outOrderId: id,
                receiverName: e["收货人"],
                receiverAddress: `${e["省"]} ${e["市"]} ${e["区"]} ${
                  e["街道"]
                }`,
                receiverTel: tel
              };

              this.checkError(order, i);

              return order;
            });

            this.showError();

            loading.close();
          };
          reader.readAsText(file.raw, "GB2312");
        }
      }
    },
    async loadTBCSV() {
      this.tableData = [];
      this.idErrorRows = [];
      this.nameErrorRows = [];
      this.addressErrorRows = [];
      this.telErrorRows = [];
      if (this.uploadFiles) {
        const loading = this.$loading({
          lock: true,
          text: "正在加载",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)"
        });
        for (let i = 0; i < this.uploadFiles.length; i++) {
          let file = this.uploadFiles[i];
          if (!file) continue;

          let csvreader = csv({
            noheader: false,
            // output: "csv",
            trim: true
          });
          let reader = new FileReader();
          reader.onload = async e => {
            const jsonArray = await csvreader.fromString(e.target.result);
            this.tableData = jsonArray.map((e, i) => {
              let idre = /(=")?(\d*)"?/;
              let id = e["订单编号"].replace(idre, "$2");
              let telre = /'?(.*)/;
              let tel = e["联系手机"].replace(telre, "$1");
              let order = {
                outOrderId: id,
                receiverName: e["收货人姓名"],
                receiverAddress: e["收货地址 "] || e["收货地址"],
                receiverTel: tel
              };

              this.checkError(order, i);

              return order;
            });

            this.showError();

            loading.close();
          };
          reader.readAsText(file.raw, "GB2312");
        }
      }
    },
    checkError(order, row) {
      let orderIDErrorRe = /E\+/;
      if (order.outOrderId.search(orderIDErrorRe) != -1) {
        this.idErrorRows.push({
          row: row,
          reason: "订单号错误"
        });
      }

      if (order.receiverName.length === 0 || order.receiverName === "null") {
        this.nameErrorRows.push({
          row: row,
          reason: "收件人姓名错误"
        });
      }

      if (
        order.receiverAddress.length === 0 ||
        order.receiverAddress === "null"
      ) {
        this.addressErrorRows.push({
          row: row,
          reason: "收件人地址错误"
        });
      }

      let orderTelErrorRe = /[0-9\-]+$/g;
      if (order.receiverTel.match(orderTelErrorRe) === null) {
        this.telErrorRows.push({
          row: row,
          reason: "收件人电话错误"
        });
      }
    },

    showError() {
      if (
        this.idErrorRows.length > 0 ||
        this.nameErrorRows.length > 0 ||
        this.addressErrorRows.length > 0 ||
        this.telErrorRows.length > 0
      ) {
        let errorTip = "";

        if (this.idErrorRows.length > 20) {
          errorTip += "订单号格式错误太多，请重新编辑<br/>";
        } else if (this.idErrorRows.length > 0) {
          errorTip +=
            this.idErrorRows.reduce((accumulator, currentValue) => {
              return accumulator + currentValue.row + ", ";
            }, "订单号错误的行：") + "<br/>";
        }

        if (this.nameErrorRows.length > 0) {
          errorTip +=
            this.nameErrorRows.reduce((accumulator, currentValue) => {
              return accumulator + currentValue.row + ", ";
            }, "收件人姓名错误的行：") + "<br/>";
        }

        if (this.addressErrorRows.length > 0) {
          errorTip +=
            this.addressErrorRows.reduce((accumulator, currentValue) => {
              return accumulator + currentValue.row + ", ";
            }, "收件人地址错误的行：") + "<br/>";
        }

        if (this.telErrorRows.length > 0) {
          errorTip +=
            this.telErrorRows.reduce((accumulator, currentValue) => {
              return accumulator + currentValue.row + ", ";
            }, "收件人电话错误的行：") + "<br/>";
        }
        this.$alert(errorTip, "上传文件错误, 请修改或删除后重新提交", {
          confirmButtonText: "确定",
          dangerouslyUseHTMLString: true
        });
      }
    },
    async fileOrderCreate() {
      const loading = this.$loading({
        lock: true,
        text: "正在加载",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      try {
        let formData = {
          giftId: this.$route.query.giftId,
          orderCode: "300101",
          outId: "asdsa",
          outType: "PDD",
          fileDetailId: this.batchFileDetailDto.id,
          kkType: this.express,
          weight: this.weight,
          addressId: this.address.id
          //   'address': this.address.address
        };

        if (this.memo !== "") {
          formData.memo = this.memo;
        }
        let result = await orderCreate(formData);
        if (result.status === 200 && result.data.code === 200) {
          let returnData = result.data.data;
          this.selectSingleOrder.outAmount = returnData.outAmount;
          this.selectSingleOrder.orderAmount = returnData.orderAmount;
          this.batchOrderDialogVisible = true;

          // this.batchFileDetailDto.id = result.data.data.id;
          this.orderConfirm.id = result.data.data.id;
        } else {
          //   this.$message({
          //     type: 'error',
          //     message: result.message
          //   })
        }
      } catch (err) {
        console.log(err);
      }
      loading.close();
    }
  }
};
</script>

<style lang="less" scoped>
@import "../../style/mixin";
.fix-width-frame {
  margin: 0 auto;
  width: 1000px;
}

.tip-container {
  padding-bottom: 30px;
  border-bottom: 1px solid #dcdcdc;
}
.tip {
  color: #555;
  font-size: 12px;
  // margin-bottom: 10px;
  // margin-left: 20px;
}
.tip span {
  color: #f82a0f;
  // font-weight: bold;
}

.table-wrapper {
  // border: 1px solid #ebeef5;
  margin: 30px 0;
}

.table-row /deep/ input {
  border-radius: 0;
  border: none;
  font-size: 14px;
  padding: 0;
  color: #222;
  height: 40px;
  // background-color: white !important;
}
.table-row /deep/ textarea {
  border: none;
  height: 150px;
}

.table-row /deep/ .el-input-group__append {
  border: none;
  background: white;
}

.table-row {
  .wh(602px, 40px);
  // border-bottom-width: 1px;
  // border-bottom-color: #ebeef5;
  // border-bottom-style: solid;
  border: 1px solid #dcdcdc;
  margin-bottom: 20px;
}

.table-row .highlighted {
  border: 1px solid #f4450c;
}

.table-cell {
  font-size: 14px;
}

.table-cell-input {
  width: 475px;
  height: 40px;
}

.table-cell-inputlabel {
  border-right: 1px solid #dcdcdc;
  width: 112px;
  display: inline-block;
  padding-left: 8px;
  font-size: 14px;
  // margin: 10px 20px;
  // min-height: 48px;
  // border-right-width: 1px;
  // border-right-color: #ebeef5;
  // border-right-style: solid;
}

.table-cell-inputlabel .highlighted {
  border-left: 1px solid #f4450c;
}

.table-header {
  // min-height: 48px;
  margin-bottom: 20px;
  font-size: 16px;
  color: #222;
  font-weight: bold;
  // border-bottom-width: 1px;
  // border-bottom-color: #ebeef5;
  // border-bottom-style: solid;
  // background: #f6f6f6;
}
// .table-header-title {
// margin-left: 10px;
// }
.label-title {
  font-weight: bold;
  font-size: 36px;
  color: #222;
  margin-top: 80px;
  margin-bottom: 20px;
  margin-left: 1px;
}
.introduct {
  width: 900px;
  margin: auto;
}
.button_submit {
  text-align: center;
}

.el-table .info-row {
  background: #c9e5f5;
}

.el-table .positive-row {
  background: #e2f0e4;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

//use
// .batch-dialog{
// width: 600px;
// }
.batch-table {
  max-height: 400px;
  overflow: auto;
}
.upload-demo {
  display: inline-block;
  margin-right: 20px;
}
// .el-tab-pane {
//   border: 1px solid #dcdcdc;
// }
</style>
